<template>
  <div class="app-container">
    <el-form ref="formRef" :disabled="!editAble" :model="form" :rules="rules" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="工序编码" prop="workProcedureCode">
            <div class="form-text">{{ form.workProcedureCode }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工序名称" prop="workProcedureName">
            <div class="form-text">{{ form.workProcedureName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工序描述" prop="remark">
            <el-tooltip
              popper-class="my-tooltip"
              class="box-item"
              effect="dark"
              :content="form.remark"
              placement="top-start"
            >
              <p style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis; margin: 0">
                {{ form.remark }}
              </p>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col v-if="!isFirstLevel" :span="6">
          <el-form-item label="单位生产时长" prop="unitProdDuration">
            <div class="form-text">{{ form.unitProdDuration }}</div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-if="!isFirstLevel" v-model="activeName" class="demo-tabs">
      <el-tab-pane v-if="checkPermi(['technology:workProcedureStation:list'])" label="岗位" name="first">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="plus"
              @click="addMat"
              v-hasPermi="['technology:workProcedureStation:add']"
            >
              添加
            </el-button>
          </el-col>
        </el-row>
        <el-table
          :data="stationTable"
          border
          :row-class-name="rowIndexMethod"
          cell-class-name="table-form-item"
          ref="whStorehouseInDetail"
        >
          <el-table-column label="序号" align="center" prop="index" width="80" />
          <el-table-column label="岗位编号" prop="stationNo"></el-table-column>
          <el-table-column label="岗位名称" prop="stationName"></el-table-column>
          <el-table-column label="岗位描述" prop="remark"></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Delete" 
                v-hasPermi="['technology:workProcedureStation:remove']"
                @click="handleDelete(scope.row, 'station')"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane v-if="checkPermi(['technology:equipment:list'])" label="设备类型" name="second">
        <el-row v-hasPermi="['technology:workProcedureType:add']" :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="plus" @click="addEquip">添加</el-button>
          </el-col>
        </el-row>
        <el-table
          :data="equipTable"
          border
          :row-class-name="rowIndexMethod"
          cell-class-name="table-form-item"
          ref="whStorehouseInDetail"
        >
          <el-table-column label="序号" align="center" prop="index" width="80" />
          <el-table-column label="设备类型编号" prop="deviceTypeNo"></el-table-column>
          <el-table-column label="设备类型名称" prop="deviceTypeName"></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                v-hasPermi="['technology:workProcedureType:remove']"
                icon="Delete"
                @click="handleDelete(scope.row, 'equip')"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <equipType v-model:show="showEqp" :data="deviceTable" @change="handleMatChange"></equipType>
    <stationDialog
      v-model:show="show"
      :data="selectTable"
      @change="handleStationChange"
    ></stationDialog>
  </div>
</template>

<script setup name="InventoryDetail">
import {
  listProcedure,
  getProcedure,
  updateProcedure,
  addProcedure,
  delProcedure,
  addStation,
  delStation,
  addType,
  delType,
} from "@/api/technology/procedure";
import equipType from "./equipType.vue";
import stationDialog from "@/components/DialogSelect/stationDialog.vue";
const attrs = useAttrs();
const { proxy } = getCurrentInstance();
const activeName = ref("first");
const refData = reactive({
  // 表单参数
  form: {},
  // 表单校验
  rules: {
    inventoryCode: [{ required: true, message: "盘点编号不能为空", trigger: "blur" }],
    inventoryName: [{ required: true, message: "主题不能为空", trigger: "blur" }],
    factoryCode: [{ required: true, message: "工厂不能为空", trigger: "blur" }],
    workshopCode: [{ required: true, message: "工段不能为空", trigger: "blur" }],
    lineCode: [{ required: true, message: "产线不能为空", trigger: "blur" }],
    storehouseName: [{ required: true, message: "线边仓不能为空", trigger: "blur" }],
    inventoryDate: [{ required: true, message: "盘点时间不能为空", trigger: "blur" }],

    status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
  },
});
const { form, rules } = toRefs(refData);
const emit = defineEmits(["close", "setActions", "setIsActionTop"]);
const inventoryDetailList = ref([]);
const operationTitle = ref("");
const showEqp = ref(false);
const show = ref(false);
const formRef = ref("formRef");
const tableForm = ref("tableForm");
const editAble = ref(false);
const formId = ref("");
const actions = ref([
  {
    text: "取 消",
    theme: "",
    handle: () => {
      cancel();
    },
  },
]);

const isFirstLevel = computed(() => {
  return !form.value.parentNo;
});
const equipTable = ref([]);
const stationTable = ref([]);
const selectTable = computed(() => {
  return stationTable.value.map((el) => {
    return { workStationCode: el.stationNo, workStationName: el.stationName };
  });
});
const deviceTable = computed(() => {
  return equipTable.value.map((el) => {
    return { code: el.deviceTypeNo, name: el.deviceTypeName };
  });
});

// 取消按钮
function cancel() {
  emit("close");
}

function checkPermi(val) {
  return proxy.checkPermi(val);
}

function addEquip() {
  showEqp.value = true;
}
function addMat() {
  show.value = true;
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    workProcedureCode: null,
    workProcedureName: null,
    workProcedureDesc: null,
    parentNo: null,
    deviceTypeNo: null,
    deviceTypeName: null,
    stationNo: null,
    stationName: null,
    unitProdDuration: null,
    remark: null,
  };
  formRef.value.resetFields();
  inventoryDetailList.value = [];
}

/** 修改按钮操作 */
function getDetail() {
  if (formId.value) {
    getProcedure(formId.value).then((response) => {
      form.value = response.data;
      stationTable.value = response.data.stations || [];
      equipTable.value = response.data.types || [];
    });
  }
}

/** 物料入仓明细删除按钮操作 */
function handleDelete(row, type) {
  let msg = "";
  if (type == "equip") {
    msg = `是否确认移除设备类型编号为${row.deviceTypeNo}数据项？`;
  } else {
    msg = `是否确认移除岗位编号为${row.stationNo}数据项？`;
  }
  proxy.$modal
    .confirm(msg)
    .then(() => {
      if (row.id) {
        if (type == "equip") {
          delType(row.id).then((res) => {
            proxy.$modal.msgSuccess("删除成功");
            getDetail();
          });
        } else {
          delStation(row.id).then((res) => {
            proxy.$modal.msgSuccess("删除成功");
            getDetail();
          });
        }
      }
    })
    .catch(() => {});
}

/** 物料入仓明细序号 */
function rowIndexMethod({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

function handleMatChange(val) {
  const currentIds = equipTable.value.map((el) => el.deviceTypeNo);
  const addData = [];
  val.forEach((el) => {
    if (!currentIds.includes(el.code)) {
      addData.push({
        deviceTypeNo: el.code,
        deviceTypeName: el.name,
        workProcedureId: form.value.id,
      });
    }
  });
  if (!addData.length) {
    proxy.$modal.msgError("设备类型重复");
    return;
  }
  addType(addData).then((res) => {
    proxy.$modal.msgSuccess("添加成功");
    getDetail();
  });
}
function handleStationChange(val) {
  const currentIds = stationTable.value.map((el) => el.stationNo);
  const addData = [];
  val.forEach((el) => {
    if (!currentIds.includes(el.workStationCode)) {
      addData.push({
        stationName: el.workStationName,
        stationNo: el.workStationCode,
        workProcedureId: form.value.id,
        remark: el.workStationDesc,
      });
    }
  });
  if (!addData.length) {
    proxy.$modal.msgError("岗位添加重复");
    return;
  }
  addStation(addData).then((res) => {
    proxy.$modal.msgSuccess("添加成功");
    getDetail();
  });
}

onMounted(() => {
  reset();
  const { data, title } = attrs;
  formId.value = data.id;
  emit("setActions", actions.value);

  getDetail();
});
</script>

<style lang="scss" scoped>
.redText {
  color: #ff0000 !important;
}
</style>
